#!/bin/bash

FILE=/proc/stat
FILEp=/tmp/proc_stat
# Time units the CPU has spent performing different kinds of work.
MODE="CPU USER NICE SYSTEM IDLE IOWAIT IRQ SOFTIRQ STEAL GUEST GUEST_NICE "

# Read numbers identify the amount of time the CPU has spent performing different kinds of work.
read $MODE < $FILE
# Check existance of previous state file
if [ ! -f $FILEp ] ; then 
    echo "Warning: There is no prev state file!"
    cat $FILE > $FILEp
    exit 1
fi
# Previous numbers
read ${MODE// /p } < $FILEp
# copy current state to file
cat $FILE > $FILEp

# calculate difference NOW - PREVIOUS, and SUM
for i in $MODE ; do
    eval $i=$(($i-${i}p))
    SUM=$((SUM+$i))
done
# Calculate the percentage, and transform it to float
for j in ${MODE#CPU } ; do
    FL=$(($j*10000/SUM))
    FL_X000=${FL: -4:1} #; FL_X000=${FL_X000:-0}
    FL_0X00=${FL: -3:1} ; FL_0X00=${FL_0X00:-0}
    FL_00X0=${FL: -2:1} ; FL_00X0=${FL_00X0:-0}
    FL_000X=${FL: -1:1} ; FL_000X=${FL_000X:-0}
    eval $j=${FL_X000}${FL_0X00}.${FL_00X0}${FL_000X}
done

echo $USER $NICE $SYSTEM $IDLE $IOWAIT $IRQ $SOFTIRQ $STEAL $GUEST
